<template>
  <el-dialog
    title="素材命名"
    :visible="visible"
    width="500px"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form label-position="left" label-width="80px">
      <el-form-item label="素材名称" size="small">
        <el-input v-model="filename" type="text" show-word-limit maxlength="100">
          <template slot="append">
            {{ append }}
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="mini" @click="onSubmit">保存</el-button>
      <el-button size="mini" @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: Boolean,
    data: Object
  },
  data() {
    return {
      filename: '',
      append: ''
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false)
    },
    onSubmit() {
      if (this.$util.isEmpty(this.filename)) {
        this.$message.warning('请填写素材名称')
        return false
      }
      this.$api.putUserTeacherMaterial(
        {
          id: this.data.id,
          title: this.filename
        },
        res => {
          this.$message.success(res.msg)
          this.$store.commit('material/SET_MATERIAL_NAME', {
            id: this.data.id,
            title: `${this.filename}.${this.append}`
          })
          this.handleClose()
        }
      )
    }
  },
  mounted() {
    let index = this.data.filename.lastIndexOf('.')
    let fileFormat = this.data.filename.substring(index + 1)
    let fileName = this.data.filename.substring(0, index)
    this.append = fileFormat
    this.filename = fileName
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  border-bottom: 1px solid #e4e7ed;
}
</style>
